﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AMS.UI.Forms;
using Spring.Context.Support;
using Spring.Context;
using AMS.DataAccess.Trademark.Interfaces;
using AMS.DataAccess.Trademark.BO;
using AMS.DataAccess.Trademark.Filters;
using AMS.Trademark.Management.Components;
using AMS.UI.Controls.Search;
using AMS.Trademark.Management.Helpers;
using AMS.Common;
using AMS.Trademark.Management.Properties;
using AMS.ComponentModel;

namespace AMS.Trademark.Management
{
    /// <summary>
    /// 一个案件的流程
    /// </summary>
    public partial class FrmRecvFileTaskConfigByCase : BaseForm
    {
        public FrmRecvFileTaskConfigByCase()
        {
            InitializeComponent();
            rfDetail.Visible = false;
            taskDetail.Visible = false;
            rfDetail.Dock = DockStyle.Fill;
            taskDetail.Dock = DockStyle.Fill;
            _searchingAdvTree = new SearchingAdvTree(tree, new SearchTextBox(txtSearchKeyword));
            
        }

        SearchingAdvTree _searchingAdvTree;
        RecvFileListDlg _rfLisgDlg;
        /// <summary>
        /// 收文列表的对话框
        /// </summary>
        RecvFileListDlg RFListDlg
        {
            get
            {
                if (_rfLisgDlg == null || _rfLisgDlg.IsDisposed)
                {
                    _rfLisgDlg = new RecvFileListDlg();
                    _rfLisgDlg.CheckRFExists += new ArgumentEventHandler<bool>(dlg_CheckRFExists);
                }
                return _rfLisgDlg;
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        public override void Init()
        {
            base.Init();
            DelayLoadData();
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        protected override void DelayLoadData()
        {
            BindCaseType();
            BindTree();
        }

        private void BindTree()
        {
            if (cmbCaseType.SelectedIndex <= 0)
            {
                tree.Nodes.Clear();
                return;
            }

            IApplicationContext context = ContextRegistry.GetContext();
            IRFTaskManager rfManager = (IRFTaskManager)context.GetObject("RFTask");
            DataTable data = rfManager.GetCaseRFTask(GetKeyFromText(cmbCaseType.SelectedItem.ToString()));

            tree.Nodes.Clear();
            if (data != null && data.Rows.Count > 0)
            {
                DevComponents.AdvTree.Node rfNode = null;
                DevComponents.AdvTree.Node taskNode = null;
                string lastRFIndex = string.Empty;
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    DataRow row = data.Rows[i];
                    string rfIndex = (string)data.Rows[i]["RFIndex"];
                    if (rfIndex != lastRFIndex)
                    {
                        rfNode = new DevComponents.AdvTree.Node();
                        rfNode.Text = string.Format("{0} - {1}", row["RFIndex"], row["RFName"]);
                        rfNode.Tag = row["RFIndex"];
                        rfNode.Cells.Add(new DevComponents.AdvTree.Cell(Convert.ToString(row["StepOrder"])));

                        tree.Nodes.Add(rfNode);
                        rfNode.ImageIndex = 0;
                        lastRFIndex = (string)row["RFIndex"];
                    }

                    taskNode = new DevComponents.AdvTree.Node();
                    taskNode.Text = string.Format("{0} - {1}", row["TaskIndex"], row["TaskName"]);
                    taskNode.Tag = row["TaskIndex"];
                    taskNode.Cells.Add(new DevComponents.AdvTree.Cell());
                    taskNode.Cells.Add(new DevComponents.AdvTree.Cell(ObjectToString(row["StartType"])));
                    taskNode.Cells.Add(new DevComponents.AdvTree.Cell(GetDeadline(row["iAddMonth"], row["iAddDay"])));
                    taskNode.Cells.Add(new DevComponents.AdvTree.Cell(GetDeadline(row["oAddMonth"], row["oAddDay"])));

                    rfNode.Nodes.Add(taskNode);
                    taskNode.ImageIndex = 1;
                }
            }

            tree.ExpandAll();
        }

        /// <summary>
        /// 绑定案件 类型下拉框
        /// </summary>
        private void BindCaseType()
        {
            IApplicationContext context = ContextRegistry.GetContext();
            IRFTaskManager rfManager = (IRFTaskManager)context.GetObject("RFTask");
            DataTable dt = rfManager.GetCaseTypes();
            cmbCaseType.Items.Clear();
            cmbCaseType.Items.Add("选择案件类型");
            foreach (DataRow row in dt.Rows)
            {
                cmbCaseType.Items.Add( string.Format("{0} - {1}", row["ID"], row["Name"]));
            }

            if (cmbCaseType.Items.Count > 0)
            {
                cmbCaseType.SelectedIndex = 0;
            }
        }

        private string GetKeyFromText(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }

            int index = text.IndexOf('-');
            if (index <= 0)
            {
                return string.Empty;
            }

            return text.Substring(0, index).Trim();
        }


        private static string ObjectToString(object value)
        {
            if (value == null || value == DBNull.Value)
            {
                return string.Empty;
            }

            return value.ToString();
        }

        private string GetDeadline(object month, object day)
        {
            string smonth = "0";
            string sday = "0";
            if (month != null && month != DBNull.Value)
            {
                smonth = Convert.ToString(month);
            }

            if (day != null && day != DBNull.Value)
            {
                sday = Convert.ToString(day);
            }

            return smonth == "0" ? sday + "天" : smonth + "月" + sday + "天";
        }

        private void chkExpandAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkExpandAll.Checked)
            {
                tree.ExpandAll();
            }
            else
            {
                tree.CollapseAll();
            }
        }

        private void tree_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProcessTreeSelectedIndexChange();
        }

        private void ProcessTreeSelectedIndexChange()
        {
            if (tree.Nodes.Count == 0 || tree.SelectedNode == null)
            {
                return;
            }
            if (tree.SelectedNode.Tag == null)
            {
                return;
            }

            string tag = tree.SelectedNode.Tag as string;
            NodeType nodeType = GetNodeType(tree.SelectedNode);
            IDetailControl selectedCtrl = null;
            if (nodeType == NodeType.RFNode)
            {
                rfDetail.Visible = true;
                taskDetail.BringToFront();
                taskDetail.Visible = false;
                selectedCtrl = rfDetail;
            }
            else if(nodeType == NodeType.TaskNode)
            {
                taskDetail.Visible = true;
                taskDetail.BringToFront();
                rfDetail.Visible = false;
                selectedCtrl = taskDetail;
            }

            if (selectedCtrl != null)
            {
                selectedCtrl.DataBind(tag);
                pnlSubTitle.Text = selectedCtrl.Title;
            }
        }

        private NodeType GetNodeType(DevComponents.AdvTree.Node node)
        {
            if (node.Parent == null)
            {
                return NodeType.RFNode;
            }
            else if (node.Parent.Parent == null)
            {
                return NodeType.TaskNode;
            }
            else
            {
                return NodeType.DocNode;
            }
        }

        private void cmbCaseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindTree();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (cmbCaseType.SelectedIndex <= 0)
            {
                MessageBox.Show(Resources.SelectCaseType);
                return;
            }

            RecvFileListDlg dlg = RFListDlg;
            if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                // Add
                var rftaskManager = ObjectUtility.GetObject<IRFTaskManager>("RFTask");
                rftaskManager.AddRFToCase(GetKeyFromText(cmbCaseType.Text), dlg.RFIndex);

                // refresh tree
                BindTree();
            }
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (cmbCaseType.SelectedIndex <= 0)
            {
                MessageBox.Show(Resources.SelectCaseType);
                return;
            }
            if (tree.SelectedNode == null || NodeType.RFNode != GetNodeType(tree.SelectedNode))
            {
                MessageBox.Show(Resources.SelectRFNode);
                return;
            }

            RecvFileListDlg dlg = RFListDlg;
            if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                // Add
                int index = int.Parse(tree.SelectedNode.Cells[0].Text);

                var rftaskManager = ObjectUtility.GetObject<IRFTaskManager>("RFTask");
                rftaskManager.InsertRFToCaseProcess(GetKeyFromText(cmbCaseType.Text), dlg.RFIndex, index);

                // refresh tree
                BindTree();
            }
        }

        void dlg_CheckRFExists(object sender, ArgumentEventArgs<bool> args)
        {
            if (tree.Nodes.Count > 0)
            {
                for (int i = 0; i < tree.Nodes.Count; i++)
                {
                    if (string.Equals(GetKeyFromText(tree.Nodes[i].Text), args.ArgumentName))
                    {
                        args.ArgumentValue = true;
                        break;
                    }
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (cmbCaseType.SelectedIndex <= 0)
            {
                MessageBox.Show(Resources.SelectCaseType);
                return;
            }
            if (tree.SelectedNode == null || NodeType.RFNode != GetNodeType(tree.SelectedNode))
            {
                MessageBox.Show(Resources.SelectRFNode);
                return;
            }

            if (DialogResult.Yes != MessageBox.Show(this, "确认从流程中删除收文吗？", "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
            {
                return;
            }

            var rftaskManager = ObjectUtility.GetObject<IRFTaskManager>("RFTask");
            rftaskManager.DeleteRFFromCase(GetKeyFromText(cmbCaseType.Text), GetKeyFromText(tree.SelectedNode.Text));

            // refresh tree
            tree.Nodes.Remove(tree.SelectedNode);
        }

        private void btnMoveUp_Click(object sender, EventArgs e)
        {
            MoveRFNode(true);
        }

        private void btnMoveDown_Click(object sender, EventArgs e)
        {
            MoveRFNode(false);
        }

        private void MoveRFNode(bool toSmallerIndex)
        {
            if (cmbCaseType.SelectedIndex <= 0)
            {
                MessageBox.Show(Resources.SelectCaseType);
                return;
            }
            if (tree.SelectedNode == null || NodeType.RFNode != GetNodeType(tree.SelectedNode))
            {
                MessageBox.Show(Resources.SelectRFNode);
                return;
            }
            if (toSmallerIndex && tree.SelectedNode.Index == 0)
            {
                return;
            }
            if (!toSmallerIndex && tree.SelectedNode.Index == tree.Nodes.Count - 1)
            {
                return;
            }

            int index = tree.SelectedNode.Index;
            int alterNodeIndex = index + 1;
            if (toSmallerIndex)
            {
                alterNodeIndex = index-1;
            }

            var rfTaskManager = ObjectUtility.GetObject<IRFTaskManager>("RFTask");
            rfTaskManager.SwapNodeOrderIndex(
                GetKeyFromText(cmbCaseType.Text),
                GetKeyFromText(tree.Nodes[index].Text),
                int.Parse(tree.Nodes[index].Cells[1].Text),
                GetKeyFromText(tree.Nodes[alterNodeIndex].Text),
                int.Parse(tree.Nodes[alterNodeIndex].Cells[1].Text));

            string tmp = tree.Nodes[alterNodeIndex].Cells[1].Text;
            tree.Nodes[alterNodeIndex].Cells[1].Text = tree.Nodes[index].Cells[1].Text;
            tree.Nodes[index].Cells[1].Text = tmp;

            DevComponents.AdvTree.Node alterNode = tree.Nodes[alterNodeIndex];
            tree.Nodes.RemoveAt(alterNodeIndex);
            tree.Nodes.Insert(index, alterNode);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            BindTree();
        }
    }

    /// <summary>
    /// 节点类型
    /// </summary>
    internal enum NodeType
    {
        Unknown,
        RFNode,
        TaskNode,
        DocNode,
    }
}
